#!/bin/env python
# coding:utf-8


from interchangeable import Tryresult
from sqlhelper import redis_result, redis_hanle
from config import redis_config
import sys
import os
from datahelper import calculation_time
import time


def logcheck(logfile):
    # 对文件进行检测是否存在并且读取
    logcheck_result = Tryresult()

    try:
        with open(logfile, 'r') as log_open_file:
            logcheck_result.data = log_open_file.readlines()
            logcheck_result.status = True

    except Exception, e:
        logcheck_result.error = e

    if logcheck_result.status:
        return logcheck_result.data

    else:
        print logcheck_result.error
        sys.exit(1)


# 处理日志
def log_handle(logfile):

    # 链接redis

    log_insert_redis = redis_hanle.RedisHelper(redis_config.game_redis_config)

    log_result = logcheck(logfile)

    # 将文件的内容转换成列表
    for line in log_result:
        line_list = line.replace('\n', '').split('\t')

        # 登陆日志
        if line_list[0] == '100':

            user_create_time = calculation_time.time_conversion(line_list[5])
            user_login_time = calculation_time.time_conversion(line_list[6])
            user_id = line_list[1]
            game_id = line_list[4]
            main_channel = line_list[2]
            sub_channel = line_list[3]

            # print user_create_time, user_login_time, user_id, game_id, main_channel, sub_channel

            log_insert_redis.user_login(user_login_time, user_create_time, main_channel, sub_channel, game_id, user_id)

        elif line_list[0] == '102':

            user_pay_time = calculation_time.time_conversion(line_list[8])
            main_channel = line_list[4]
            sub_channel = line_list[5]
            game_id = line_list[9]
            user_id = line_list[3]
            pay_money = line_list[13]
            order_id = line_list[1]


            log_insert_redis.user_pay(user_pay_time, main_channel, sub_channel, game_id, user_id, pay_money, order_id)





if __name__ == '__main__':

    count = 0
    start_time = time.time()
    os.chdir('../logdata')
    b = os.listdir(os.getcwd())
    for i in b:
        print '正在处理文件%s' % i

        log_handle(i)
        count += 1

    end_time = time.time()
    use_time = end_time - start_time


    log_select_redis = redis_result.RedisHelper(redis_config.game_redis_config)
    select_main_channel = '10031000'
    select_sub_channel = '10031004'
    select_time = '2016-06-14'
    select_game_id = '10038'


    print log_select_redis.select_time_result(select_time, select_main_channel, select_sub_channel, select_game_id)
